#include <bits/stdc++.h>
using namespace std;
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
using ll = long long;
const ll N = 13;
ll a[N][N];
ll fx[] = {-1, -1, 0, 1, 1, 1, 0, -1};
ll fy[] = {0, 1, 1, 1, 0, -1, -1, -1};
ll vis[N][N];
vector<ll> t[1000];
ll cnt = 0, ct = 0;
ll n, k;
bool f = 0;
ll edge[N][N][N][N];
string ans;
void dfs(ll x, ll y, ll dep)
{
	if(f)
		return;
	if (x == n  && y == n  && dep == n*n - 1)
	{
		cout << ans << endl;
		f = 1;
		return;
	}

	for (ll i = 0; i < 8; i++)
	{
		ll nx = x + fx[i], ny = y + fy[i];
		if (nx <= 0 || nx > n || ny > n || ny <= 0)
			continue;
		if (vis[nx][ny])
			continue;
		if ((i == 1) && (edge[x - 1][y][x][y + 1] || edge[x][y + 1][x - 1][y]))
			continue;
		if ((i == 3) && (edge[x + 1][y][x][y + 1] || edge[x][y + 1][x + 1][y]))
			continue;
		if ((i == 5) && (edge[x][y - 1][x + 1][y] || edge[x + 1][y][x][y - 1]))
			continue;
		if ((i == 7) && (edge[x - 1][y][x][y - 1] || edge[x][y - 1][x - 1][y]))
			continue;
		if(a[nx][ny]!=(a[x][y]+1)%k)
			continue;

			vis[nx][ny] = 1;
			edge[x][y][nx][ny] = 1;
			ans.push_back('0' + i);
			dfs(nx, ny, dep + 1);
			ans.pop_back();
			vis[nx][ny] = 0;
			edge[x][y][nx][ny] = 0;

	}
}
void solve()
{

	cin >> n >> k;
	for (ll i = 1; i <= n; i++)
	{
		for (ll j = 1; j <= n; j++)
		{
			cin >> a[i][j];
		}
	}

	if(a[1][1]!=0) {
		cout << -1 << endl;
		return;
	}
	vis[1][1] = 1;

	dfs(1, 1, 0);

	if(f==0)
	{
		cout << -1 << endl;
	}
}
int main()
{
	int t = 1;
	// cin >> t;
	while (t--)
	{
		solve();
	}
	return 0;
}
